<template>
  <el-dialog v-model="visible" title="修改密码" width="850px" :close-on-click-modal="false">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" placeholder="请输入原密码" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" placeholder="请输入新密码" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" placeholder="请再次输入新密码" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { updatePassword } from '@/api/modules/login'
import { ElMessage } from "element-plus";
const visible = ref(false);
const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const passwordValidator = (rule: any, value: any, callback: any) => {
  const reg = /((^(?=.*[a-z])(?=.*[A-Z])(?=.*[\!\@\#\$\%\^\&\*\(\)\_\+\-\=])[\da-zA-Z\!\@\#\$\%\^\&\*\(\)\_\+\-\=]{8,32}$)|(^(?=.*\d)(?=.*[A-Z])(?=.*[\!\@\#\$\%\^\&\*\(\)\_\+\-\=])[\da-zA-Z\!\@\#\$\%\^\&\*\(\)\_\+\-\=]{8,32}$)|(^(?=.*\d)(?=.*[a-z])(?=.*[\!\@\#\$\%\^\&\*\(\)\_\+\-\=])[\da-zA-Z\!\@\#\$\%\^\&\*\(\)\_\+\-\=]{8,32}$)|(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z\!\@\#\$\%\^\&\*\(\)\_\+\-\=]{8,32}$))/
  if (!value) {
    return callback(new Error('请输入原密码'));
  } else if (reg.test(value)) {
    callback();
  } else {
    return callback(new Error('密码必须包含三种及以上类型：大写字母、小写字母、数字、特殊符号。长度为8～32位。特殊字符包括! @ # $ % ^ & * () _ + - ='));
  }
};
const confirmValidator = (rule: any, value: any, callback: any) => {
  const { newPassword } = form
  if (!value) {
    return callback(new Error('请再次输入新密码'))
  }
  if (newPassword !== value) {
    return callback(new Error('两次输入密码不一致'))
  }
  callback()
}

const rules = ref({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, trigger: ['blur', 'change'], validator: passwordValidator }
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', validator: confirmValidator }
  ],
})
const openDialog = () => {
  visible.value = true;
};
const formRef = ref()
function handleClose () {
  visible.value = false
  formRef.value!.resetFields()
}
function handleSubmit () {
  formRef.value!.validate(async(valid: boolean) => {
    if (valid) {
      await updatePassword(form)
      ElMessage.success({ message: '操作成功' });
      handleClose()
    }
  })
}


defineExpose({ openDialog });
</script>
